using System.Linq;
using FluentDBC.Extensions;

namespace FluentDBC.Default
{
    public class ConditionEngine<TModel> : IConditionEngine<TModel>
    {
        private readonly IFluentDBCConfiguration _codeContractFactory;
        private readonly IFieldContract<TModel> _fieldContract;
        private readonly string _fieldName;

        public ConditionEngine(IFluentDBCConfiguration codeContractFactory, IFieldContract<TModel> fieldContract, string fieldName)
        {
            _codeContractFactory = codeContractFactory;
            _fieldContract = fieldContract;
            _fieldName = fieldName;
        }

        public IValidationContractEngine<TModel> PreCondition()
        {
            AssignCondition(true);

            return new ValidationContractEngine<TModel>(_codeContractFactory, _fieldContract, _fieldName, true);
        }

        public IValidationContractEngine<TModel> PostCondition()
        {
            AssignCondition(false);

            return new ValidationContractEngine<TModel>(_codeContractFactory, _fieldContract, _fieldName, false);
        }

        private void AssignCondition(bool isPrecondition)
        {
            for (var i = 0; i < _codeContractFactory.ClassContracts.Count; i++)
            {
                var element = _codeContractFactory.ClassContracts.ElementAt(i);

                if (element.Type.TypeCompare(_fieldContract.ClassObj))
                {
                    for (var j = 0; j < element.Fields.Count; j++)
                    {
                        if (element.Fields[j].FieldName.CultureEquals(_fieldName))
                        {
                            element.Fields[j].Precondition = isPrecondition;
                        }
                    }
                }
            }
        }
    }
}